package com.topone.controller;

import com.topone.Exception.FanZoneException;
import com.topone.Form.CouponCategoryForm;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.CouponCategory;
import com.topone.service.CouponCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/15,0015.
 */
@CrossOrigin
@RestController
@RequestMapping("/seller/category")
@Slf4j
public class SellerCategoryController {

    @Autowired
    private CouponCategoryService categoryService;

    @GetMapping("/list")
    public ResultVO<Map<String,Object>> list(Map<String,Object> map){

        List<CouponCategory> categoryList=categoryService.findAll();
        map.put("categoryList",categoryList);
        return ResultVOUntil.success(map);
    }

    @GetMapping("/index")
    public ResultVO index(@RequestParam(value = "categoryId",required = false) Integer categoryId,
                          Map<String,Object> map){


        if(categoryId !=null){
            CouponCategory couponCategory=categoryService.findOne(categoryId);
            map.put("couponCategory",couponCategory);
            log.info("根据categoryId查询优惠券类型成功,{}",map);
        }
        return ResultVOUntil.success(map);
    }

    @PostMapping("/save")
    public ResultVO save(@Valid CouponCategoryForm categoryForm,
                         BindingResult bindingResult){
        Map<String,Object> map=new HashMap<>();
        if(bindingResult.hasErrors()){
            log.info("输入参数有问题");
            return ResultVOUntil.error(1,"输入参数有问题");
        }
        CouponCategory couponCategory=new CouponCategory();
        try {
            if(categoryForm.getCategoryId()!=null){
                couponCategory=categoryService.findOne(categoryForm.getCategoryId());
            }
            BeanUtils.copyProperties(categoryForm,couponCategory);
            categoryService.save(couponCategory);
        }catch (FanZoneException e){
            return ResultVOUntil.error(1,e.getMessage());
        }
        map.put("success","新增优惠券种类成功");
        return ResultVOUntil.success(map);

    }
}
